'''
Created on 2020年11月11日

@author: Administrator
'''
import datetime
import os, xlwt
from urllib.parse import quote

from flask import make_response
from flask import send_file
from peewee import JOIN, fn

from common.public import *
from orm.model import RegistrationSheet, User, RegistSupplement
from view.baseview import BaseView


class MyRegistratorView(BaseView):

    def __init__(self):
        pass

    def export(self, params):
        print(params)
        where_condition = True
        if params["founddate"]:
            where_condition = where_condition & ((RegistSupplement.invitee_date >= params["founddate"][0] + " 00:00:00") \
                                               & (RegistSupplement.invitee_date <= params["founddate"][1] + " 23:59:59"))            
        wb = xlwt.Workbook()
        ws = wb.add_sheet('招聘信息')
        first_col = ws.col(0)  # xlwt中是行和列都是从0开始计算的
        second_col = ws.col(1)
        third_col = ws.col(2)
        four_col = ws.col(3)
        five_col = ws.col(4)
        six_col = ws.col(5)
        seven_col = ws.col(6)
        eight_col = ws.col(7)
        nine_col = ws.col(8)
        ten_col = ws.col(9)
        first_col.width = 128 * 20
        second_col.width = 230 * 20
        third_col.width = 230 * 20
        four_col.width = 128 * 20
        five_col.width = 230 * 20
        six_col.width = 128 * 20
        seven_col.width = 128 * 20
        eight_col.width = 128 * 20
        nine_col.width = 128 * 20
        ten_col.width = 230 * 20
        ws.write(0, 0, "面试时间")
        ws.write(0, 1, "姓名")
        ws.write(0, 2, "联系方式")
        ws.write(0, 3, "专业")
        ws.write(0, 4, "学历")
        ws.write(0, 5, "面试岗位")
        ws.write(0, 6, "是否通过")
        ws.write(0, 7, "来源")
        ws.write(0, 8, "邀约人")
        ws.write(0, 9, "面试人")
        ws.write(0, 10, "备注")
        rows = RegistrationSheet.select(RegistrationSheet.name, RegistrationSheet.tel, RegistrationSheet.major, RegistrationSheet.remake
                    , RegistrationSheet.educationlist, RegistrationSheet.position, RegistrationSheet.pass_type
                    , RegistSupplement.invitee_date, RegistSupplement.invitees, RegistSupplement.first_tester).join(RegistSupplement, JOIN.LEFT_OUTER, on = (RegistSupplement.r_id == RegistrationSheet.id)).where(where_condition)
        if rows is not None:
            for i in range(0, len(rows)):
                pet = rows[i]
                if pet.registsupplement.invitee_date != None:
                    pet.registsupplement.invitee_date = time.strftime("%Y-%m-%d", time.strptime(str(pet.registsupplement.invitee_date), "%Y-%m-%d %H:%M:%S"))
                # if pet.repairDate is not None:
                ws.write(i + 1, 0, pet.registsupplement.invitee_date)
                ws.write(i + 1, 1, pet.name)
                ws.write(i + 1, 2, pet.tel)
                ws.write(i + 1, 3, pet.major)
                ws.write(i + 1, 4, pet.educationlist)
                ws.write(i + 1, 5, pet.position)
                ws.write(i + 1, 6, pet.pass_type)
                ws.write(i + 1, 7, '')
                ws.write(i + 1, 8, pet.registsupplement.invitees)
                ws.write(i + 1, 9, pet.registsupplement.first_tester)
                ws.write(i + 1, 10, pet.remake)
        timerange = params["founddate"][0] + "-" + params["founddate"][1]
        path = "/static/excel/"
        fileName = "招聘信息" + timerange + ".xls"
        file_path = ROOT_PATH + path
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        file_path = file_path + fileName
        try:
            f = open(file_path, 'r')
            f.close()
        except IOError:
            f = open(file_path, 'w')
        wb.save(file_path)
        data = make_response(send_file(file_path))
        # 自定义的一个header，方便前端取到名字
        data.headers['filename'] = quote(fileName.encode('utf-8'))
        return data

        # return super().resultSet(200, "导出成功")
    def checkNameDistinct(self, params):
        """
        检查用户名和电话号码有没有重复
        """
        checkPass = super().resultSet(200, "姓名检查通过", {})
        usernameNopass = super().resultSet(420, "姓名不能重复。", {})
        userfind = User.select().where(User.username == params["name"]).first()
        if userfind:
            return usernameNopass
#             if userfind.id == params["id"]:
#                 return checkPass
#             else:
#                 return usernameNopass
        return checkPass
    
    def checkPhoneDistinct(self, params):
        """
        检查用户名和电话号码有没有重复
        """
        checkPass = super().resultSet(200, "检查电话号码通过", {})
        phoneNopass = super().resultSet(420, "电话不能重复。", {})
        phonfind = User.select().where(User.phone == params["tel"]).first()
        if phonfind:
            return phoneNopass
#             if phonfind.id == params["id"]:
#                 return checkPass
#             else:
#                 return phoneNopass
        else:
            return checkPass
    def adduser(self, params): 
        checkname = self.checkNameDistinct(params)
        checkphone = self.checkPhoneDistinct(params)
        if checkname["code"] == 200:
            if checkphone["code"] == 200:
                print(params["identityCard"][-6:])
                user = User.create(
                            username = params["name"],
                            password = params["identityCard"][-6:],
                            isactive = "是",
                            ismanager = "否",
                            isleader = "否",
                            dept_id = params["deptId"],
                            status = "在职",
                            sex = params["sex"],
                            birthday = params["birthday"],
                            address = params["residentialAddress"],
                            phone = params["tel"],
                            idcards = "[]",)
                return super().resultSet(200, "添加成功", []) 
            else:
                return checkphone
        else:
            return checkname
        raise Exception("用户添加失败")
    def updateMyRegistor(self, params):
        registrationsheet = RegistrationSheet.get(RegistrationSheet.identity_card == params["identityCard"])
        registrationsheet.name = params["name"]
        registrationsheet.sex = params["sex"]
        registrationsheet.birthday = params["birthday"]
        registrationsheet.position = params["position"]
        registrationsheet.local = params["local"]
        registrationsheet.marital_status = params["maritalStatus"]
        registrationsheet.tel = params["tel"]
        registrationsheet.registered_permanent_residence = params["registeredPermanentResidence"]
        registrationsheet.residential_address = params["residentialAddress"]
        registrationsheet.urgent_name = params["urgentName"]
        registrationsheet.urgent_tel = params["urgentTel"]
        registrationsheet.salary_expectation = params["salaryExpectation"]
        registrationsheet.fastest_work_time = params["fastestWorkTime"]
        registrationsheet.learn_start_time = params["learnStartTime"]
        registrationsheet.learn_end_time = params["learnEndTime"]
        registrationsheet.school_name = params["schoolName"]
        registrationsheet.examination_type = params["examinationType"]
        registrationsheet.major = params["major"]
        registrationsheet.graduate_type = params["graduateType"]
        registrationsheet.educationlist = params["educationList"]
        registrationsheet.remake = params["remake"]
        registrationsheet.pass_type = params["passType"]
        registrationsheet.open_bank = params["openBank"]
        registrationsheet.account_number = params["accountNumber"]
        registrationsheet.remind = params["remind"]
        if params["remindTime"]:
            registrationsheet.remind_time = params["remindTime"]
        else:
            registrationsheet.remind_time = None
        registrationsheet.remind_content = params["remindContent"]
        registrationsheet.save()
        registsupplement, created = RegistSupplement.get_or_create(r_id = registrationsheet.id, defaults = {'add_time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())})
        print(registsupplement, created)
        registsupplement = RegistSupplement.get(RegistSupplement.r_id == registrationsheet.id)
        registsupplement.invitees = params["invitees"]
        registsupplement.source = params["source"]
        registsupplement.invitee_date = params["inviteeDate"]
        registsupplement.first_tester = params["firstTester"]
        registsupplement.retester = params["reTester"]
        registsupplement.ft_comment = params["ftComment"]
        registsupplement.rt_comment = params["rtComment"]
        registsupplement.update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        registsupplement.save()
        return super().resultSet(200, "更新成功", [])
    
    def queryMyRegistor(self, params):
        """根据条件取得我的客户列表，params：条件参数"""
        result=[]
        where_condition = True
        if params["inviteeDate"]:
            where_condition = where_condition & ((RegistSupplement.invitee_date >= params["inviteeDate"][0] + " 00:00:00") \
                                               & (RegistSupplement.invitee_date <= params["inviteeDate"][1] + " 23:59:59"))
        if params["addTime"]:
            where_condition = where_condition & ((RegistrationSheet.add_time >= params["addTime"][0] + " 00:00:00") \
                                               & (RegistrationSheet.add_time <= params["addTime"][1] + " 23:59:59"))
        if params["updateTime"]:
            where_condition = where_condition & ((RegistrationSheet.update_time >= params["updateTime"][0] + " 00:00:00") \
                                               & (RegistrationSheet.update_time <= params["updateTime"][1] + " 23:59:59"))
        if params["remindTime"]:
            where_condition = where_condition & ((RegistrationSheet.remind_time >= params["remindTime"][0] + " 00:00:00") \
                                               & (RegistrationSheet.remind_time <= params["remindTime"][1] + " 23:59:59"))
        if params["local"]:
            where_condition = where_condition & (RegistrationSheet.local.in_(params["local"]))
        if params["position"]:
            where_condition=where_condition &(RegistrationSheet.position ==(params["position"]))
        if params["perfectFlag"]:
            if params["perfectFlag"] == '已完善':
                where_condition = where_condition & (RegistrationSheet.perfect_flag == '已完善')
            else:
                where_condition = where_condition & (RegistrationSheet.perfect_flag == '未完善')
        if params["name"]:
           # where_condition=where_condition &(RegistrationSheet.name ==(params["name"]))
            likestr = "%" + params["name"] + "%"
            where_condition = where_condition & (RegistrationSheet.name ** likestr)
        if params["identityCard"]:
            where_condition=where_condition &(RegistrationSheet.identity_card ==(params["identityCard"]))
        rows = RegistrationSheet.select().join(RegistSupplement, JOIN.LEFT_OUTER, \
               on = (RegistSupplement.r_id == RegistrationSheet.id)).where(where_condition)\
                .order_by(RegistrationSheet.add_time.desc(), RegistrationSheet.remind_time.desc(),
                          RegistrationSheet.update_time.desc())
        total = rows.count()
        rows = rows.paginate(int(params["pageNo"]), int(params["pagesize"]))
        remind_flag = False 
        for row in rows:
            registsupplement = RegistSupplement.get_or_create(r_id = row.id)
            registsupplement = RegistSupplement.get(RegistSupplement.r_id == row.id)
            if registsupplement.invitee_date != None:
                registsupplement.invitee_date = time.strftime("%Y-%m-%d %H:%M:%S", time.strptime(str(registsupplement.invitee_date), "%Y-%m-%d %H:%M:%S")) 
            if row.add_time != None:
                row.add_time = time.strftime("%Y-%m-%d", time.strptime(str(row.add_time), "%Y-%m-%d %H:%M:%S"))
            if row.update_time != None:
                row.update_time = time.strftime("%Y-%m-%d", time.strptime(str(row.update_time), "%Y-%m-%d %H:%M:%S"))
            if row.remind_time != None:
                d1 = row.remind_time 
                d2 = datetime.datetime.now()
                d3 =  d1+ datetime.timedelta(days = 7)
                # 现在时候超过提醒时间开始提醒
                if d1 < d2 < d3:
                    remind_flag = True
                else:
                    remind_flag = False
                row.remind_time = time.strftime("%Y-%m-%d", time.strptime(str(row.remind_time), "%Y-%m-%d %H:%M:%S"))
            
            data = {
                "id":row.id,
                "name":row.name,
                "sex":row.sex,
                "birthday":row.birthday,
                "local":row.local,
                "position":row.position,
                "maritalStatus":row.marital_status,
                "identityCard":row.identity_card,
                "tel":row.tel,
                "registeredPermanentResidence":row.registered_permanent_residence,
                "residentialAddress":row.residential_address,
                "urgentName":row.urgent_name,
                "urgentTel":row.urgent_tel,
                "salaryExpectation":row.salary_expectation,
                "fastestWorkTime":row.fastest_work_time,
                "learnStartTime":row.learn_start_time,
                "learnEndTime":row.learn_end_time,
                "schoolName":row.school_name,
                "examinationType":row.examination_type,
                "major":row.major,
                "educationList":row.educationlist,
                "graduateType":row.graduate_type,
                "addTime":row.add_time,
                "updateTime":row.update_time,
                "nation":row.nation,
                "stature":row.stature,
                "weight":row.weight,
                "eMail":row.e_mail,
                "certificateLevel":row.certificate_level,
                "englishLevel":row.english_level,
                "selfComment":row.self_comment,
                "specialty":row.specialty,
                "health":row.health,
                "workexperience":row.workexperience,
                "family":row.family,
                "perfectFlag": row.perfect_flag,
                "remake": row.remake,
                "imgURL":row.imgbase64,
                "passType": row.pass_type,
                "openBank": row.open_bank,
                "accountNumber":row.account_number,
                "remind":row.remind,
                "remindTime":row.remind_time,
                "remindContent":row.remind_content,
                "remindFlag":remind_flag,
                "invitees":registsupplement.invitees,
                "inviteeDate":registsupplement.invitee_date,
                "source":registsupplement.source,
                "firstTester":registsupplement.first_tester,
                "ftComment":registsupplement.ft_comment,
                "reTester":registsupplement.retester,
                "rtComment":registsupplement.rt_comment
             }
            result.append(data)
        return super().resultSet(200, "", result,total=total)


if __name__ == '__main__':
    view = MyRegistratorView()
    data = view.queryMyRegistor()
    
#    
